package com.yungu.swift.api.route.v1.passenger.h5;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.api.utils.RandomUtil;
import com.yungu.swift.assets.driver.service.CarModelValuationService;
import com.yungu.swift.assets.passenger.model.dto.PassengerDto;
import com.yungu.swift.assets.passenger.service.PassengerService;
import com.yungu.swift.autoconfig.redis.RedisCacheService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.common.model.dto.CommonIdentifyDto;
import com.yungu.swift.common.service.CommonSmsService;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.MagicConstant;
import com.yungu.swift.order.model.dto.OrderDto;
import com.yungu.swift.order.service.OrderFareService;
import com.yungu.swift.order.service.OrderService;
import com.yungu.swift.system.marketing.service.MarketingInviteLogService;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.ValidateUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@RequestMapping(value = "/h5/passenger")
public class PassengerH5Controller {
    @Reference
    private OrderService orderService;
    @Reference
    private OrderFareService orderFareService;
    @Reference
    private CarModelValuationService carModelValuationService;
    @Reference
    private PassengerService passengerService;
    @Reference
    private CommonSmsService commonSmsService;
    @Reference
    private MarketingInviteLogService marketingInviteLogService;
    @Autowired
    private RedisCacheService redisCacheService;

    @RequestMapping(value = {"/cancelRule"}, method = {RequestMethod.POST, RequestMethod.GET})
    public String cancelRule(@RequestParam String appid, @RequestParam String orderUuid, Model model) {
        OrderDto orderDto = orderService.get(MapUtils.build("uuid", orderUuid)).getData();
        if (orderDto != null) {
            if (CommonConstant.BUSINESS_TYPE_TAXI == orderDto.getTypeTrip()) {
                model.addAttribute("carTypeName", "出租车");
            }
            if (CommonConstant.BUSINESS_TYPE_SPEC == orderDto.getTypeTrip()) {
                model.addAttribute("carTypeName", "专车");
            }
            if (CommonConstant.BUSINESS_TYPE_EXPRESS == orderDto.getTypeTrip()) {
                model.addAttribute("carTypeName", "快车");
            }
        }
        return appid + "/cancelRule";
    }

    @RequestMapping(value = {"/userAgreement"}, method = {RequestMethod.POST, RequestMethod.GET})
    public String index(@RequestParam String appid) {
        return appid + "/passengerAgreement";
    }

    @RequestMapping(value = {"/goodsAgreement"}, method = {RequestMethod.POST, RequestMethod.GET})
    public String goodsAgreement(@RequestParam String appid) {
        return appid + "/goodsAgreement";
    }

    @RequestMapping(value = {"/register/identifyCode/send"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "新乘客被邀请注册发送验证码", notes = "校验是否新乘客，是否已被邀请，是否是自己邀请自己，校验通过则发送验证码", response = ResponseData.class)
    public ResponseData<Boolean> send(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam(value = "appid") String appid,
            @ApiParam(name = "inviter", value = "邀请人手机号码", required = true) @RequestParam(value = "inviter") String inviter,
            @ApiParam(name = "inviterType", value = "邀请人类型（1乘客,2司机）", required = true) @RequestParam(value = "inviterType") Integer inviterType,
            @ApiParam(name = "invitee", value = "被邀请人手机号码", required = true) @RequestParam(value = "invitee") String invitee,
            HttpServletRequest request) {
        if (!ValidateUtils.validateMobile(invitee)) {
            return ResponseData.buildErrorResponse(100, null);
        }
        //校验是否自己邀请自己
        if (inviter.trim().equals(invitee.trim())) {
            return ResponseData.buildErrorResponse(102, null);
        }
        //判断是否有接受过邀请
        Map<String, Object> params = MapUtils.build();
        //被邀请人手机号
        params.put("invitee", invitee);
        //被邀请为乘客
        params.put("inviteeType", 1);
        int count = marketingInviteLogService.count(params).getData();
        //如果已被邀请
        if (count > 0) {
            return ResponseData.buildErrorResponse(103, null);
        }
        //判断是否在乘客表中存在
        params.clear();
        params.put("mobile", invitee);
        Object object = passengerService.get(params).getData();
        //老用户
        if (object != null) {
            return ResponseData.buildErrorResponse(104, null);
        }
        return commonSmsService.sendAliIdentify(invitee, appid);
    }

    @ApiOperation(value = "新乘客注册接口", notes = "返回成功或失败消息")
    @RequestMapping(value = {"/register"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResponseData register(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam(value = "appid") String appid,
            @ApiParam(name = "identifyCode", value = "验证码", required = true) @RequestParam(value = "identifyCode") String identifyCode,
            @ApiParam(name = "inviter", value = "邀请人手机号码", required = true) @RequestParam(value = "inviter") String inviter,
            @ApiParam(name = "inviterType", value = "邀请人类型（1乘客,2司机）", required = true) @RequestParam(value = "inviterType") Integer inviterType,
            @ApiParam(name = "invitee", value = "被邀请人手机号码", required = true) @RequestParam(value = "invitee") String invitee,
            @ApiParam(name = "areacode", value = "区域编码", required = true) @RequestParam(value = "areacode") String areacode) {

        Map<String, Object> paramMap = MapUtils.build(3);
        String decryptIdentifyCode = RandomUtil.randomDecrypt(identifyCode);
        if (decryptIdentifyCode.length() != MagicConstant.INT_FOUR) {
            return ResponseData.buildErrorResponse(101, "请输入正确的验证码");
        }
        //校验是否自己邀请自己
        if (inviter.trim().equals(invitee.trim())) {
            return ResponseData.buildErrorResponse(102, null);
        }
        //判断是否有接受过邀请
        Map<String, Object> params = MapUtils.build();
        //被邀请人手机号
        params.put("invitee", invitee);
        //被邀请为乘客
        params.put("inviteeType", 1);
        int count = marketingInviteLogService.count(params).getData();
        //如果已被邀请
        if (count > 0) {
            return ResponseData.buildErrorResponse(103, null);
        }
        //判断是否在乘客表中存在
        params.clear();
        params.put("mobile", invitee);
        ResponseData<PassengerDto> responseData = passengerService.get(params);
        //老用户
        if (responseData.isSuccess() && responseData.getData() != null) {
            return ResponseData.buildErrorResponse(104, "");
        }
        //校验验证码是否存在 && 同一个手机号保证三分钟内只能输入5次
        ResponseData identifyData = ResponseData.buildErrorResponse(101, "");
        //一个手机号的注册次数
        int registerCount = 1;
        Object object = redisCacheService.get("PassengerRegisterCount" + invitee);
        if (object != null) {
            registerCount = (int) object;
        }
        if (registerCount > MagicConstant.INT_FIVE) {
            identifyData.setErrCode(107);
            return identifyData;
        }

        String mobileTop3 = invitee.substring(0, 3);
        CommonIdentifyDto identify = null;
        if (!mobileTop3.equals(MagicConstant.STRING_ONE_FOUR_TWO)) {
            paramMap.put("mobile", invitee);
            paramMap.put("identifyCode", decryptIdentifyCode);
            paramMap.put("status", CommonConstant.IDENTIFY_CODE_STATUS_UNUSED);
            paramMap.put("appid", appid);
            identify = commonSmsService.get(paramMap).getData();
        }

        if (mobileTop3.equals(MagicConstant.STRING_ONE_FOUR_TWO) || identify != null) {
//           passengerService.
            //注册成功 则用户的验证码设置为已使用
            if (!mobileTop3.equals(MagicConstant.STRING_ONE_FOUR_TWO)) {
                //更新验证码
                identify.setStatus(CommonConstant.IDENTIFY_CODE_STATUS_USED);
                commonSmsService.edit(identify);
            }
            Map map = MapUtils.build();
            map.put("inviter", inviter);
            map.put("inviterType", inviterType);
            map.put("appid", appid);
            map.put("invitee", invitee);
            map.put("adCode", areacode);
            //注册成功，删除缓存
            redisCacheService.delete("PassengerRegisterCount" + invitee);
            return passengerService.inviteRegister(map);
        } else {
            registerCount++;
            redisCacheService.set("PassengerRegisterCount" + invitee, registerCount, 3L);
            identifyData.setErrCode(101);
            return identifyData;
        }
    }
}
